package com.kotodama.infrastructure.config;

import com.kotodama.infrastructure.tenant.connection.MultiTenantConnectionProviderImpl;
import com.kotodama.infrastructure.tenant.filter.CurrentTenantIdentifierResolverImpl;
import java.util.Map;
import javax.sql.DataSource;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Hibernate多租户配置
 * 配置多租户策略和相关组件
 */
@Configuration
public class HibernateConfig {

    /**
     * 多租户连接提供者
     */
    @Bean
    public MultiTenantConnectionProvider multiTenantConnectionProvider(DataSource dataSource) {
        return new MultiTenantConnectionProviderImpl(dataSource);
    }

    /**
     * 当前租户标识符解析器
     */
    @Bean
    public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() {
        return new CurrentTenantIdentifierResolverImpl();
    }

    /**
     * Hibernate属性自定义器
     * 配置多租户相关属性
     */
    @Bean
    public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(
            MultiTenantConnectionProvider multiTenantConnectionProvider,
            CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {

        return new HibernatePropertiesCustomizer() {
            @Override
            public void customize(Map<String, Object> hibernateProperties) {
                // 配置多租户策略（Hibernate 6.x 使用字符串常量）
                hibernateProperties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
                hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
                
                // 对于 Hibernate 6.x，不再需要显式设置 MULTI_TENANCY 属性

                // 禁用默认模式过滤器
                hibernateProperties.put("hibernate.tenant_identifier_resolver",
                        currentTenantIdentifierResolver);
            }
        };
    }
}